<?php
namespace app\crm\model;

use think\facade\Db;
use app\admin\model\Common;
use app\admin\model\ShopModel;

class CustomerAccountLog extends Common
{
    protected $name = 'customer_account_log';

    //列表
    public function getAccountLog(array $param): array
    {
        $page = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? 10;
        $where = array();
        if(!empty($param['customer_id']))
        {
            $where[] = ['a.customer_id','=',$param['customer_id']];
        }
        if(!empty($param['notes']))
        {
            $where[] = ['a.notes','=',$param['notes']];
        }
        if(!empty($param['order_id']))
        {
            $where[] = ['a.order_id','=',$param['order_id']];
        }
        if(!empty($param['order_type']))
        {
            $where[] = ['a.order_type','=',$param['order_type']];
        }
        if(!empty($param['start']) || !empty($param['end']))
        {
            if(!empty($param['start']))
            {
                $start = strtotime($param['start'].'00:00:00');
            }else
            {
                $start = strtotime(time().'00:00:00');
            }
            if(!empty($param['end']))
            {
                $end = strtotime($param['end'].'23:59:59');
            }else
            {
                $end = strtotime(time().'23:59:59');
            }
            $where[] = ['a.create_time','between',[$start, $end]];
        }
        // 门店
        if(!empty($param['shop_id']))
        {
            $where[] = ['s.shop_id','=',$param['shop_id']];
        }elseif(!empty($param['shopIds']))
        {
            $where[] = ['s.shop_id','in',$param['shopIds']];
        }

        // 账户展示方式
        if(!empty($param['action']) && $param['action'] == 'zhanghu')
        {
            $res = Db::name('customer_account_log')
            ->where($where)
            ->field([
                'a.order_id',
                'a.order_type',
                'a.customer_id',
                'a.symbol',
                "FROM_UNIXTIME(a.create_time, '%Y-%m-%d %H:%i:%s') as create_time",
                'MAX(a.remarks) AS remarks',

                // 本金变化金额（带符号）
                "SUM(IF(a.type = 2, 
                    CASE 
                        WHEN a.symbol = 1 THEN a.amount 
                        WHEN a.symbol = 2 THEN -a.amount 
                        ELSE 0 
                    END, 
                0)) AS amount_change",

                // 赠金变化金额（带符号）
                "SUM(IF(a.type = 3, 
                    CASE 
                        WHEN a.symbol = 1 THEN a.amount 
                        WHEN a.symbol = 2 THEN -a.amount 
                        ELSE 0 
                    END, 
                0)) AS gift_change",

                // 本金余额（操作后）
                "MAX(IF(a.type = 2, a.now_amount, NULL)) AS now_amount",

                // 赠金余额（操作后）
                "MAX(IF(a.type = 3, a.now_amount, NULL)) AS now_gift",

                // 总变化金额（本金+赠金）
                "SUM(
                    CASE 
                        WHEN a.symbol = 1 THEN a.amount 
                        WHEN a.symbol = 2 THEN -a.amount 
                        ELSE 0 
                    END
                ) AS total_change_amount",

                // 总余额（本金+赠金）
                "SUM(IF(a.type = 2, a.now_amount, 0)) + 
                 SUM(IF(a.type = 3, a.now_amount, 0)) AS total_now_balance",

                'c.customer_name',
                'c.telephone',
                's.shop_name',
                't.name as notes_name'
            ])
            ->alias('a')
            ->leftJoin('customer c', 'a.customer_id = c.id')
            ->leftJoin('customer_account ac', 'a.customer_id = ac.id')
            ->leftJoin('shop s', 'c.shop_id = s.shop_id')
            ->leftJoin('setting t', 'a.notes = t.id')
            ->group('a.order_id, a.create_time, a.order_type, a.customer_id')
            ->order('a.create_time', 'desc')
            ->paginate([
                'list_rows' => $pagesize,
                'page' => $page,
                'query' => request()->param()
            ]);
            $res = json_decode(json_encode($res),true);
            return $res;
        }else
        {
            // 流水展示方式
            if(!empty($param['type']))
            {
                $where[] = ['a.type','=',$param['type']];
            }
            $res = [];

            $res = $this->order('a.create_time','desc')->where($where)
            ->field('a.*, c.customer_name, c.telephone, s.shop_name, t.name as notes_name')
            ->alias('a')
            ->leftJoin('customer c','a.customer_id = c.id')
            ->leftJoin('shop s','c.shop_id = s.shop_id')
            ->leftJoin('setting t','a.notes = t.id')
            ->paginate([
                'list_rows'=>$pagesize,
                'page'=>$page,
                'query'=>request()->param()
            ]);
            $res = json_decode(json_encode($res),true);
            return $res;
        }

    }

    //添加方法
    public function addAccountLog(array $request): array
    {
        //判断必传参数
        $requiredFields = [
            'customer_id' => '顾客ID',
            'last_amount' => '变更前金额',
            'amount' => '变更金额',
            'now_amount' => '变更后金额',
            'symbol' => '变更符号',
            'type' => '变更类型',
            'notes' => '类型备注ID',
        ];
        foreach ($requiredFields as $field => $name)
        {
            if (!array_key_exists($field, $request))
            {
                $this->error = "{$name}不能为空";
                return false;
            }
        }

        //如果金额不为0
        if($param['amount'] >= 0.01)
        {
            $insert_data['order_id'] = $param['order_id']??"";
            $insert_data['order_type'] = $param['order_type']??"";
            $insert_data['customer_id'] = $param['customer_id'];
            $insert_data['last_amount'] = $param['last_amount'];
            $insert_data['amount'] = $param['amount'];
            $insert_data['now_amount'] = $param['now_amount'];
            $insert_data['symbol'] = $param['symbol'];
            $insert_data['type'] = $param['type'];
            $insert_data['notes'] = $param['notes'];
            $insert_data['remarks'] = $param['remarks']??"";
            $insert_data['create_time'] = time();
            $this->insertGetId($insert_data);
        }
    }

}
